package ext.tianma.part.finishedProduct.processors;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.csm.navigation.ClassificationNode;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.iba.definition.litedefinition.AttributeDefDefaultView;
import wt.log4j.LogR;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.workflow.work.WfAssignedActivity;
import wt.workflow.work.WorkItem;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.core.meta.common.impl.TypeIdentifierUtilityHelper;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.generic.workflow.WorkflowUtil;
import ext.tianma.bom.util.CSCIBA;
import ext.tianma.part.finishedProduct.util.CSMUtil;
import ext.tianma.part.finishedProduct.util.IBAUtil;
import ext.tianma.part.finishedProduct.util.InterfaceUtil;
import ext.tianma.part.finishedProduct.util.TypesUtil;
import ext.tianma.part.finishedProduct.vo.ClassAttrRuleVo;



public class EditFinishedGoodAttrsProcessors extends DefaultObjectFormProcessor {
	private static Logger log = LogR.getLogger(EditFinishedGoodAttrsProcessors.class.getName());

	@Override
	public FormResult doOperation(NmCommandBean arg0, List<ObjectBean> arg1) throws WTException {
		log.debug("EditFinishedGoodAttrsProcessors==>>Start");
		FormResult formresult = new FormResult();
		formresult.setStatus(FormProcessingStatus.SUCCESS);
	
		NmOid nmoid = arg0.getActionOid();
		WTPart currentPart = (WTPart) nmoid.getRefObject();	
	    ClassificationNode node = CSMUtil.getClassNodeByPart(currentPart);

		try {
			/**
			 * add by xucr 根据节点信息，获取对应的workitem，并判断workitem是否是当前登录者的任务
			 * */
			WTUser loginUser = (WTUser) SessionHelper.manager.getPrincipal();
			String activityOid = arg0.getRequest().getParameter("activityOid");
			ReferenceFactory rf = new ReferenceFactory();
			WfAssignedActivity activity = (WfAssignedActivity) rf.getReference(activityOid).getObject();
			QueryResult workitmes = WorkflowUtil.getWorkItemByParent(activity);
			boolean isClosed = false;
			String message = "";
			while (workitmes.hasMoreElements()) {
				WorkItem workItem = (WorkItem) workitmes.nextElement();
				WTPrincipalReference user = workItem.getOwnership().getOwner();
				user.getPrincipal().getPersistInfo().getObjectIdentifier().getId();
				
				/**
				 * 逻辑说明：
				 * 1、某个节点下，不会给同一个人分配多个workitem
				 * 2、如果某个节点产生了多个workitem，这里我们只考虑当前登陆者的workitem
				 * 3、权限：当他人如果在非正常或者特殊情况下进入了别人的任务页面，也不能有权限编辑
				 * */
				if(loginUser.getName().equals(user.getName())) {//进入自己的任务
					if("已完成".equals(workItem.getStatus().getDisplay())) {
						isClosed = true;
						message = "当前任务已关闭，无法继续编辑！";
					}
				} else {
					isClosed = true;
					message = "您不是当前任务的责任人，无法编辑！";
				}
			}
			
			if(isClosed) {
				throw new WTException(message);
			}
			
			//获取节点下所有属性<内部名称，显示名称>
		    Map<String, String> classNodeAllIBAs = CSMUtil.getClassNodeAllIBAs(node);
		    log.debug("classNodeAllIBAs==>>"+classNodeAllIBAs);
		    //获取页面所有属性
		    HashMap<String, List<String>> allPageAttrs = getAllPageAttrs(currentPart,arg0);
		    log.debug("allPageAttrs==>>"+allPageAttrs);
		    //获取分类属性
		    HashMap<String, String> classAttrsMap = getClassAttrsMap(allPageAttrs,classNodeAllIBAs);
		    log.debug("classAttrsMap==>>"+classAttrsMap);
		    //校验分类属性
		    validationClassAttrs(currentPart,classAttrsMap,node);
		    
		    //保存属性
			setPartAttrs(currentPart,allPageAttrs,node,classNodeAllIBAs);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new WTException(e.getLocalizedMessage());
		}
		
		formresult.setNextAction(FormResultAction.JAVASCRIPT);
		String js = "window.close();";
		formresult.setJavascript(js);
		return formresult;
	}

	/**
	 * 获取页面上的所有属性
	 * @param part
	 * @param clientData
	 * @param node
	 * @return
	 */
	public static HashMap<String, List<String>> getAllPageAttrs(WTPart part,NmCommandBean clientData){
		//下拉列表、文本框、
  		HashMap<String,List<String>> attrsInfoCombox = clientData.getComboBox();//下拉列表
  		log.debug("attrsInfoCombox==>>"+attrsInfoCombox);
  		HashMap<String,String> attrsInfoText = clientData.getText();//文本框 包含其它后面的框
  		log.debug("attrsInfoText==>>"+attrsInfoText);
  		HashMap<String, List<String>> allIBAAttrs = new HashMap<String,List<String>>();    
	    for(Entry<String, List<String>> enty : attrsInfoCombox.entrySet()){
	    	String key = enty.getKey().split("_")[0];
	    	List<String> valueList = enty.getValue();
	    	if(allIBAAttrs.containsKey(key)){
	    		valueList.addAll(allIBAAttrs.get(key));
	    		allIBAAttrs.put(key, valueList);
	    	}else{
	    		allIBAAttrs.put(key, valueList);
	    	}	    	
	    }
	    
	    for(Entry<String, String> enty : attrsInfoText.entrySet()){
	    	String key = enty.getKey().split("_")[0];
	    	String value = enty.getValue();
	    	List<String> list = new ArrayList<String>();
	    	if(allIBAAttrs.containsKey(key)){
	    		list = allIBAAttrs.get(key);
	    	}else{
	    	}	
	    	list.add(value);
	    	allIBAAttrs.put(key, list);
	    }
		return allIBAAttrs;
	}
	
	public static HashMap<String, String> getClassAttrsMap(HashMap<String, List<String>> allIBAAttrs,
			Map<String, String> classNodeAllIBAs){
		HashMap<String,String> classAttrsMap = new HashMap<String, String>();
		for(Entry<String, List<String>> enty : allIBAAttrs.entrySet()){
			if(classNodeAllIBAs.containsKey(enty.getKey())){
				List<String> valueList = enty.getValue();
				String value = "";
				for(String tempValue : valueList){
					value = value + tempValue + ",";
				}
				
				if(StringUtils.isNotEmpty(value)){
					value = value.substring(0, value.lastIndexOf(","));
				}
				
				classAttrsMap.put(enty.getKey(),value );
			}
		}
		return classAttrsMap;
	}
	
	public static void validationClassAttrs(WTPart part,HashMap<String, String> classAttrsMap,ClassificationNode node) throws RemoteException, WTException{

		InterfaceUtil.sendCheckService(part, classAttrsMap,node);
	}
	
    public static void setPartAttrs(WTPart part,HashMap<String, List<String>> allIBAAttrs,
    		ClassificationNode node,Map<String, String> classNodeAllIBAs) throws WTException, RemoteException{
	    //保存属性
	    for(Entry<String, List<String>> enty : allIBAAttrs.entrySet()){
	    	String key = enty.getKey();
	    	List<String> valueList = enty.getValue();
	    	List<String> tempList = new ArrayList<String>();
	    	for(String value : valueList){
	    		if(null != value && value.length() > 0){
	    			tempList.add(value);
	    		}
	    	}
	    	boolean isClassAndSingle = false;
	        try {
	        	if(classNodeAllIBAs.containsKey(key)){
	        		ClassAttrRuleVo	classAttrRuleVo = CSMUtil.getClassAttrInfo(node, key);
	        		if(classAttrRuleVo.getSingleValued()){
	        			isClassAndSingle = true;
	        		}
	        	}
				IBAUtil.setIBAAnyValues((WTObject)part, key,tempList,isClassAndSingle);
			} catch (Exception e) {
				e.printStackTrace();
				String displayName = "";
				AttributeDefDefaultView attributedefdefaultview = CSCIBA.getAttributeDefinition(key, false);
				if(null == attributedefdefaultview){
					displayName = TypesUtil.getAttrDisplayName("cn.tianma.FinishedGood", key);
				}else{
					displayName = attributedefdefaultview.getDisplayName();
				}
				throw new WTException("属性'"+ displayName + "':" +e.getLocalizedMessage());
			}
	    }
    }
}
